package com.hxy.manager.activity.today;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.hxy.manager.R;
import com.hxy.manager.activity.ViewHolder;
import com.hxy.manager.entity.TodayPriceEntity;

import java.util.Vector;

/**
 * Created by 傲寒宏志 on 2018/1/13.
 */

public class TodayActivity extends Activity {
    ListView listView;
    //ListView列表适配器
    private BaseAdapter listViewAdapter;
    //当前选择
    private int selecteItem = 0;
    TodayPriceEntity[] TP;
    TodayPriceEntity todayPrice[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.today);
        setTitle("今日菜价");

        getActionBar().setDisplayHomeAsUpEnabled(true);//向上返回
        listView = (ListView) findViewById(R.id.listView1);
        LoadToday();

    }

    //修改后重新加载
    @Override
    protected void onResume() {
        super.onResume();
        //  LoadToday();//这个会导致每次点击进去之后都重新像第一次进入一样，从第一个开始显示。
        //解决办法：更新数据，刷新列表即可。

        SQLiteDatabase db = openOrCreateDatabase("My_DB.db", MODE_PRIVATE, null);


        //这地方存在逻辑错误！因为一开的时候数据虽然存在，但是下面这个表不存在！
        //主键的数据类型必须是整型
        db.execSQL("create table if not exists TodayPrice(id integer primary key autoincrement, name text,price text,date text,photo text,time text)");

        Cursor cursor = db.rawQuery("select * from TodayPrice", null);

        Vector<TodayPriceEntity> vector = new Vector<TodayPriceEntity>();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                TodayPriceEntity tp = new TodayPriceEntity();
                tp.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex("id"))));
                tp.setName(cursor.getString(cursor.getColumnIndex("name")));
                tp.setPrice(cursor.getString(cursor.getColumnIndex("price")));
                tp.setDate(cursor.getString(cursor.getColumnIndex("date")));
                tp.setPhoto(cursor.getString(cursor.getColumnIndex("photo")));
                vector.add(tp);
            }
            //迭代器转化成数组！
            TP = vector.toArray(new TodayPriceEntity[]{});

        }

        cursor.close();
        db.close();


        //刷新列表
        listViewAdapter.notifyDataSetChanged();
    }


    public void LoadToday() {


        SQLiteDatabase db = openOrCreateDatabase("My_DB.db", MODE_PRIVATE, null);


        //这地方存在逻辑错误！因为一开的时候数据虽然存在，但是下面这个表不存在！
        //主键的数据类型必须是整型
        db.execSQL("create table if not exists TodayPrice(id integer primary key autoincrement, name text,price text,date text,photo text,time text)");

        Cursor cursor = db.rawQuery("select * from TodayPrice", null);

        Vector<TodayPriceEntity> vector = new Vector<TodayPriceEntity>();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                TodayPriceEntity tp = new TodayPriceEntity();
                tp.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex("id"))));
                tp.setName(cursor.getString(cursor.getColumnIndex("name")));
                tp.setPrice(cursor.getString(cursor.getColumnIndex("price")));
                tp.setDate(cursor.getString(cursor.getColumnIndex("date")));
                tp.setPhoto(cursor.getString(cursor.getColumnIndex("photo")));
                vector.add(tp);
            }
            //迭代器转化成数组！
            TP = vector.toArray(new TodayPriceEntity[]{});

        }

        cursor.close();
        db.close();

        //获取所有通讯录联系人
        // MakeTable ct = new MakeTable(this);
        // users = ct.getAllData();
        //listView列表实现适配器

        listViewAdapter = new BaseAdapter() {


            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                ViewHolder holder;
                //加入,这个类是自定义的静态类。

                if (convertView == null) {


                    final LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.today_item, null);
                    holder = new ViewHolder();
                    //    holder.icon=(ImageView)convertView.findViewById(R.id.imageView);
                    holder.name = (TextView) convertView.findViewById(R.id.nameView);
                    holder.price = (TextView) convertView.findViewById(R.id.priceView);
                    convertView.setTag(holder);

                } else {
                    holder = (ViewHolder) convertView.getTag();
                }


                //这个地方需要文件读写权限呢，没有权限，会一直为null！
                //所以安卓6.0以上需要加入一些代码解决！
                // Bitmap bmp = BitmapFactory.decodeFile(TP[position].getPhoto());
                //    holder.icon.setImageResource(R.drawable.store);
                // holder.icon.setImageBitmap(bmp);
                holder.name.setText(TP[position].getName());
                holder.price.setText(TP[position].getPrice());


                if (position == selecteItem) {
                    convertView.setBackgroundColor(0x5f1296db);
                    //	Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
                } else {
                    convertView.setBackgroundColor(0);
                }
                return convertView;
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return position;
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return TP[position];
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return TP.length;
            }
        };
        //设置listView控件的适配器
        listView.setAdapter(listViewAdapter);
        //长按
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

                                                @Override
                                                public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                                                               int arg2, long arg3) {
                                                    // TODO Auto-generated method stub
                                                    selecteItem = arg2;
                                                    //    Toast.makeText(Today.this,"长按修改",Toast.LENGTH_SHORT).show();
                                                    //    if(TP[selecteItem].getNumber()!=null){
                                                    //        Intent intent3 = new Intent(Today.this,Update.class);
                                                    //        intent3.putExtra("scanCode", TP[selecteItem].getNumber());
                                                    //        startActivity(intent3);
                                                    //    }
                                                    //   else {
                                                    //        Toast.makeText(Store.this, "没有联系人",Toast.LENGTH_SHORT).show();
                                                    //   }

                                                    return true;

                                                }
                                            }
        );
        //短按
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub

                //记录单击列的位置
                selecteItem = arg2;
                //刷新列表
                listViewAdapter.notifyDataSetChanged();

                Intent intent = new Intent(TodayActivity.this, TodayShowActivity.class);
                intent.putExtra("id", String.valueOf(TP[selecteItem].getId()));
                Log.i("kan", "传入id值" + String.valueOf(TP[selecteItem].getId()));
                startActivity(intent);
                Log.i("kan", "启动Today_show");


            }

        });


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.today, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:  //默认添加的，左边的TItle向上返回
                finish();
                break;
            case R.id.action_add://保存
                startActivity(new Intent(TodayActivity.this, TodayAddActivity.class));
                //  Toast.makeText(Store.this,"点击了添加！",Toast.LENGTH_SHORT).show();
                break;
            case R.id.action_find:
                //   Toast.makeText(this, "点击了查询！", Toast.LENGTH_LONG).show();
                new FindDialog(this).show();
                break;
            case R.id.action_statistics:

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("统计");
                //04  builder.setIcon(R.drawable.scan);
                //下一步进行主页面adapter的列表自定义。

                builder.setMessage("菜品：" + TP.length + " 种");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                    }
                });
                builder.create();
                builder.show();
                break;
                /*
            case R.id.action_logs:
                startActivity(new Intent(Today.this,Logs.class));
                //  Toast.makeText(Store.this,"点击了添加！",Toast.LENGTH_SHORT).show();
                break;

*/

        }
        return false;

    }

    //内部类？********************/
    public class FindDialog extends Dialog {

        public FindDialog(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.find);
            setTitle("查询");
            //点击查询自动弹出虚拟键盘
            EditText value = (EditText) findViewById(R.id.value);
            value.setFocusable(true);
            value.setFocusableInTouchMode(true);
            value.requestFocus();
            this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

            Button find = (Button) findViewById(R.id.find);
            Button cancel = (Button) findViewById(R.id.cancel);
            find.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    EditText value = (EditText) findViewById(R.id.value);
                    String values = value.getText().toString().trim();
                    SQLiteDatabase db = openOrCreateDatabase("My_DB.db", MODE_PRIVATE, null);
                    db.execSQL("create table if not exists TodayPrice(id integer primary key autoincrement, name text,price text,date text,photo text,time text)");

                    //  Cursor cursor= db.rawQuery("select * from TodayPrice where ",null);
                    Log.i("kan", "输入值：" + values);
                    Cursor cursor = db.rawQuery("select * from TodayPrice where name like \"%" + values + "%\" ", null);

                    Vector<TodayPriceEntity> vector = new Vector<TodayPriceEntity>();
                    while (cursor.moveToNext()) {
                        TodayPriceEntity tp = new TodayPriceEntity();
                        tp.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex("id"))));
                        tp.setName(cursor.getString(cursor.getColumnIndex("name")));
                        tp.setPrice(cursor.getString(cursor.getColumnIndex("price")));
                        tp.setDate(cursor.getString(cursor.getColumnIndex("date")));
                        tp.setPhoto(cursor.getString(cursor.getColumnIndex("photo")));
                        vector.add(tp);
                    }
                    Log.i("kan", "查询得到的数据长度：" + String.valueOf(vector.size()));
                    todayPrice = vector.toArray(new TodayPriceEntity[]{});


                    listViewAdapter = new BaseAdapter() {


                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {

                            ViewHolder holder;
                            //加入,这个类是自定义的静态类。

                            if (convertView == null) {


                                final LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                convertView = inflater.inflate(R.layout.today_item, null);
                                holder = new ViewHolder();
                                //    holder.icon=(ImageView)convertView.findViewById(R.id.imageView);
                                holder.name = (TextView) convertView.findViewById(R.id.nameView);
                                holder.price = (TextView) convertView.findViewById(R.id.priceView);
                                convertView.setTag(holder);

                            } else {
                                holder = (ViewHolder) convertView.getTag();
                            }


                            //这个地方需要文件读写权限呢，没有权限，会一直为null！
                            //所以安卓6.0以上需要加入一些代码解决！
                            // Bitmap bmp = BitmapFactory.decodeFile(TP[position].getPhoto());
                            //    holder.icon.setImageResource(R.drawable.store);
                            // holder.icon.setImageBitmap(bmp);
                            holder.name.setText(todayPrice[position].getName());
                            holder.price.setText(todayPrice[position].getPrice());


                            if (position == selecteItem) {
                                convertView.setBackgroundColor(0x5f1296db);
                                //	Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
                            } else {
                                convertView.setBackgroundColor(0);
                            }
                            return convertView;
                        }

                        @Override
                        public long getItemId(int position) {
                            // TODO Auto-generated method stub
                            return position;
                        }

                        @Override
                        public Object getItem(int position) {
                            // TODO Auto-generated method stub
                            return todayPrice[position];
                        }

                        @Override
                        public int getCount() {
                            // TODO Auto-generated method stub
                            return todayPrice.length;
                        }
                    };
                    //设置listView控件的适配器
                    listView.setAdapter(listViewAdapter);
                    //长按
                    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

                                                            @Override
                                                            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                                                                           int arg2, long arg3) {
                                                                // TODO Auto-generated method stub
                                                                selecteItem = arg2;
                                                                //    Toast.makeText(Today.this,"长按修改",Toast.LENGTH_SHORT).show();
                                                                //    if(TP[selecteItem].getNumber()!=null){
                                                                //        Intent intent3 = new Intent(Today.this,Update.class);
                                                                //        intent3.putExtra("scanCode", TP[selecteItem].getNumber());
                                                                //        startActivity(intent3);
                                                                //    }
                                                                //   else {
                                                                //        Toast.makeText(Store.this, "没有联系人",Toast.LENGTH_SHORT).show();
                                                                //   }

                                                                return true;

                                                            }
                                                        }
                    );
                    //短按
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                                long arg3) {
                            // TODO Auto-generated method stub

                            //记录单击列的位置
                            selecteItem = arg2;
                            //刷新列表
                            listViewAdapter.notifyDataSetChanged();

                            Intent intent = new Intent(TodayActivity.this, TodayShowActivity.class);
                            intent.putExtra("id", String.valueOf(todayPrice[selecteItem].getId()));
                            Log.i("kan", "传入id值" + String.valueOf(todayPrice[selecteItem].getId()));
                            startActivity(intent);
                            Log.i("kan", "启动Today_show");


                        }

                    });


                    dismiss();//关闭Dialog

                }
            });
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    dismiss();
                }
            });
        }
    }


}
